package top.riske.animalhazardassessment.common.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import top.riske.animalhazardassessment.common.DTO.JwtDto;
import top.riske.animalhazardassessment.common.enums.RoleEnum;
import top.riske.animalhazardassessment.common.http.response.Result;
import top.riske.animalhazardassessment.common.utils.ResponseUtils;

import java.io.IOException;

/**
 * 管理员权限过滤器，保护所有/protected/admin开头的路径
 * created by vital on 2025/3/1 下午3:01
 */
@Slf4j
public class AdminRoleFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 判断是否是http请求
        if(!(servletRequest instanceof HttpServletRequest)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        // 强制转换为http请求
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        // 从请求头中提取身份信息
        JwtDto jwtDto = (JwtDto) httpRequest.getAttribute(AuthorizationFilter.AUTHORIZATION_DATA_HEADER);
        // 判断是否是管理员
        if(!jwtDto.getRole().equals(RoleEnum.ADMIN)){
            // 返回错误信息，无权限
            Result<Object> result = Result.fail("无管理员权限", null);
            ResponseUtils.setErrorResponse(httpRequest, httpResponse, result);
            return;
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("AdminRoleFilter初始化");
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        log.info("AdminRoleFilter销毁");
        Filter.super.destroy();
    }
}
